<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('表对象信息列表')" />
    <th:block th:include="include :: datetimepicker-css" />
    <style>
        .fixed-table-toolbar{
            display: none;
        }
        .select-list li input{
            display: inline;
            width: 160px;
        }
        .btn-sm {
            padding: 5px 10px;
            font-size: 12px;
            line-height: 1.5;
            margin-left: 5px;
        }
        .dropdown-item-marker label {
            display: block;
            padding: 3px 20px;
            clear: both;
            font-weight: 400;
            line-height: 1.428571429;
        }
        .dropdown-menu {
            right: 0;
            left: auto;
        }
        .dropdown-menu {
            text-align: left;
            max-height: 300px;
            overflow: auto;
            -ms-overflow-style: scrollbar;
            z-index: 1001;
            width: 200px;
        }
        /*.select-list li{*/
        /*    width: 28%;*/
        /*}*/
        .select-list li p, .select-list li label:not(.radio-box){
            width: 120px;
        }
    </style>
</head>
<body class="gray-bg">
<div class="container-div">
    <input type="hidden" name="tableEnName" th:value="${tableEnName}">
    <input type="hidden" name="tableName" th:value="${tableName}">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <div style="height: 30px;">
                <div class="keep-open btn-group pull-right" title="列">
                    <button class="btn btn-default btn-outline dropdown-toggle" type="button" data-toggle="dropdown" aria-label="Columns" title="列" aria-expanded="false">
                        <i class="glyphicon glyphicon-th icon-th"></i>

                        <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu" role="menu" id="dropdownMenu">
                    </ul>
                </div>
            </div>
            <form id="formId">
                <div class="select-list" id="searchrow"></div>
            </form>
        </div>
        <div class="col-sm-12 select-table table-striped">
            <table id="bootstrap-table"></table>
        </div>
    </div>

</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: layout-latest-js" />
<th:block th:include="include :: datetimepicker-js" />
<script id="columnSelectTpl" type="text/template">
    {{# layui.each(d, function(index, a){ }}
    <li class="dropdown-item-marker" role="menuitem">
        <label>
            <input type="checkbox"  value="{{a.mysqlfieldname}}" onclick="checkboxClick()" > <span>{{a.fieldname}}</span>
        </label>
    </li>
    {{# }); }}
</script>
<script th:inline="javascript">
    var prefix = "http://code.suzhi.link:8070";
    // var prefix = "http://127.0.0.1:9099";
    var tableId = [[${tableId}]];
    var searchInfo = [];
    var columns = [];
    var searchParamsField = [];
    var enumList = [];
    $(function() {
        fieldInfoList();
        var tableEnName = $("input[name='tableEnName']").val();
        var options = {
            url: prefix + "/tTableInfo/queryByPage",
            queryParams: function (params) {
                return{
                    "current": Math.ceil(params.offset/params.limit) + 1,
                    "params": {
                        "tableId": tableId,
                        "tableName": tableEnName,
                        "searchInfoList": searchInfo
                    },
                    "size": params.limit
                }
            },
            contentType:"application/json",
            modalName: "表对象信息",
            columns:columns
        };
        $.table.init(options);
    });
    $("body").on("click",".fieldChoose",function () {
        var id = $(this).data("id");
        var options = {
            title: '字段数据选择',
            height: "600",
            url: ctx + "table/table/tableFieldChoose/" + id,
            btn: ['确定', '取消'],
            callBack: function (index, layero) {
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.submitHandler(index, layero);
                return false;
            }
        };
        $.modal.openOptions(options);
    })
    // 获取字段
    var fkInfo = {}; var fieldList=[];
    function fieldInfoList() {
        let config = {
            url: prefix + "/tFieldInfo/queryFiledInfo",
            type: "post",
            dataType: "json",
            contentType:"application/json",
            async:false,
            data: JSON.stringify({
                "tableId": tableId
            }),
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function (result) {
                $.modal.closeLoading();
                if (result.errCode == 1) {
                    fkInfo = result.data.find(function(e){return e.fieldtype==='1'});
                    fieldList = result.data;
                    var columnSelectTplHtml = $("#columnSelectTpl").html();
                    laytpl(columnSelectTplHtml).render(result.data, function (html) {
                        $("#dropdownMenu").empty();
                        $("#dropdownMenu").append(html);
                    });
                    result.data.forEach((e) =>{
                        // if(columns.length>=6){
                        //     return false
                        // }
                        e.mysqlfieldname.indexOf("_time")==-1 && columns.push(Object.assign({}, {title: e.fieldname, field: e.mysqlfieldname, width: 200}))
                    })
                    columns.push({
                        title: '操作',
                        align: 'center',
                        formatter: function(value, row, index) {
                            var actions = [];
                            actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="tabUpdate(\'' + encodeURIComponent(JSON.stringify(row))+ '\',\'' +index+ '\')"><i class="fa fa-edit"></i>查看</a> ');
                            actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="delRow(\'' + encodeURIComponent(JSON.stringify(row))+ '\')"><i class="fa fa-remove"></i>删除</a> ');
                            return actions.join('');
                        },
                        width: 200
                    })
                    return false;
                }
                if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.message)
                    return false;
                }
                $.modal.alertError(result.message);
            }
        };
        $.ajax(config);
    }
    //表数据详情
    function tabUpdate(data,index) {
        var tableEnName = $("input[name='tableEnName']").val();
        var tableName = $("input[name='tableName']").val();
        window.sessionStorage.setItem("tableInfo"+"_"+tableId+"_"+index,data);
        $.modal.openTab("表对象信息",
            ctx + "table/table/tabUpdate/" + tableId +"/" + index +"?name=" + encodeURIComponent(tableName)+"&enname=" + encodeURIComponent(tableEnName));
    }
    function queryTable() {
        searchInfo = [];
        getSearchInfo();
        $.table.refresh();
    }

    function getSearchInfo (){
        searchParamsField.forEach((e)=>{
                if(e.isfieldenum == 'Y'){
                var operatorSelectValue = $('select[name=' + e.mysqlfieldname+ '_1select' + ']').val();
                var selectValue = $('select[name=' + e.mysqlfieldname + ']').val();
                searchInfo.push({
                    "fieldName": e.mysqlfieldname,
                    "searchValue": selectValue,
                    "operator": operatorSelectValue
                });
            }else if(e.fielddatatype == '3'){
                var operatorSelectValue = $('select[name=' + e.mysqlfieldname+ '_1select' + ']').val();
                var inputValue = $('input[id=' + e.mysqlfieldname + ']').val();
                searchInfo.push({
                    "fieldName": e.mysqlfieldname,
                    "searchValue": inputValue,
                    "operator": operatorSelectValue
                });
            }else{
                var operatorSelectValue = $('select[name=' + e.mysqlfieldname+ '_1select' + ']').val();
                var inputValue = $('input[name=' + e.mysqlfieldname + ']').val();
                searchInfo.push({
                    "fieldName": e.mysqlfieldname,
                    "searchValue": inputValue,
                    "operator": operatorSelectValue
                });
            }
        });
    }

    function getFiledEnum(obj) {
        // 页面大图
        let config = {
            url: prefix+"/tFieldInfo/queryFiledEnum",
            type: "post",
            dataType: "json",
            contentType:"application/json",
            async:false,
            data: JSON.stringify({
                "tableId": obj.id
            }),
            success: function (result) {
                if (result.errCode == 1) {
                    enumList = [];
                    result.data.forEach((e) =>{
                        var optionElm = $("<option" + " value=" + e.dictValue + ">"+e.dictLabel + "</option>");
                        enumList.push(optionElm);
                    })
                    return false;
                }
                if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.message)
                    return false;
                }
                $.modal.alertError(result.message);
            }
        };
        $.ajax(config);
    }
    /**
     * 删除行
     * @param 行数据
     */
    function delRow(row){
        $.modal.confirm("确定删除吗？", function() {
            row = JSON.parse(decodeURIComponent(row));
            var tableEnName = $("input[name='tableEnName']").val();
            let config = {
                url: prefix + "/dataManager/deleteBusinessData",
                type: "post",
                dataType: "json",
                contentType:"application/json",
                async:false,
                data: JSON.stringify({
                    "tableName": tableEnName,
                    "values": [
                        {
                            "fieldName": fkInfo.mysqlfieldname,
                            "value": row[fkInfo.mysqlfieldname],
                        }
                    ]
                }),
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍后...");
                },
                success: function (result) {
                    $.modal.closeLoading();
                    if (result.errCode == 1) {
                        $.modal.alertSuccess("删除成功");
                        $.modal.closeLoading();
                        queryTable();
                    }else{
                        $.modal.alertError(result.message);
                    }
                }
            }
            $.ajax(config);
        })
    }
    /**
     * 新增
     */
    function addRow(){
        var tableEnName = $("input[name='tableEnName']").val();
        var tableName = $("input[name='tableName']").val();
        window.sessionStorage.removeItem("tableInfo"+"_"+tableId+"_0");
        $.modal.openTab("表对象信息",
            ctx + "table/table/tabUpdate/" + tableId +"/0" + "?name=" + encodeURIComponent(tableName)+"&enname=" + encodeURIComponent(tableEnName));
    }

    function reset() {
        $("#searchrow input").val("");
        searchParamsField.forEach((e)=>{
            $("#"+e.mysqlfieldname+ "_2select" +" option:first").prop("selected", 'selected');
            $("#"+e.mysqlfieldname+ "_1select" +" option:first").prop("selected", 'selected');
        });
        searchInfo = [];

    }
    // 选择事件
    var selectFieldList = [];
    var oldSearchInfo = [];
    function checkboxClick(){
        selectFieldList = [];
        getSearchInfo();
        oldSearchInfo = searchInfo;
        $('.keep-open .dropdown-item-marker').find(':checkbox').each(function(){
            if ($(this).is(":checked") && !/^[0-9]+$/.test($(this).val())) {
                selectFieldList.push(fieldList.find((e)=>e.mysqlfieldname==$(this).val()))
            }
        });
        getSearchParamsField(selectFieldList);
    }
    /**
     * 获取搜索字段
     * @param data
     */
    function getSearchParamsField(data){
        searchInfo = [];
        searchParamsField = [];
        var ul = $("<ul></ul>");
       data.forEach((e) =>{
           var searchObj = oldSearchInfo.length>0 ? oldSearchInfo.find(e1=>e1.fieldName == e.mysqlfieldname)||{}:{};
           console.log('searchObj', searchObj);
           if (e.isfieldenum == 'Y') {
            var commonSelect = $("<select style='width: 80px'></select>").attr({
                name: e.mysqlfieldname+"_1select",
                id: e.mysqlfieldname+"_1select"
            });
            var eaualOp = $("<option value=\"EQUAL\">等于</option>");
            var greaterOp = $("<option value=\"GREATER\">大于</option>");
            var lessthanOp = $("<option value=\"LESSTHAN\">小于</option>");
            var greaterEqualOp = $("<option value=\"GREATER_EAUAL\">大于等于</option>");
            var lessthanEqualOp = $("<option value=\"LESSTHAN_EQUAL\">小于等于</option>");
            var likeOp = $("<option value=\"LIKE\">模糊</option>");
            commonSelect.append(eaualOp);
            commonSelect.append(greaterOp);
            commonSelect.append(lessthanOp);
            commonSelect.append(greaterEqualOp);
            commonSelect.append(lessthanEqualOp);
            commonSelect.append(likeOp);
            searchObj.operator && commonSelect.find("option[value='"+searchObj.operator+"']").attr("selected",true);
            var select = $("<select style='width: 80px'></select>").attr({
                name: e.mysqlfieldname,
                id: e.mysqlfieldname + "_2select"
            });
            select.append("<option value=\"\">所有</option>");
            var label = $("<label>"+e.fieldname+"：</label>");
            getFiledEnum(e);
            enumList.forEach((em) =>{
                select.append(em);
            });
            searchObj.searchValue && select.find("option[value='"+searchObj.searchValue+"']").attr("selected",true);
            var li = $("<li></li>").append(label).append(commonSelect).append(select);
            ul.append(li);
            }else if(e.fielddatatype == '3'){

                var commonSelect = $("<select style='width: 80px'></select>").attr({
                    name: e.mysqlfieldname+"_1select",
                    id: e.mysqlfieldname+"_1select"
                });
                var eaualOp = $("<option value=\"EQUAL\">等于</option>");
                var greaterOp = $("<option value=\"GREATER\">大于</option>");
                var lessthanOp = $("<option value=\"LESSTHAN\">小于</option>");
                var greaterEqualOp = $("<option value=\"GREATER_EAUAL\">大于等于</option>");
                var lessthanEqualOp = $("<option value=\"LESSTHAN_EQUAL\">小于等于</option>");
                var likeOp = $("<option value=\"LIKE\">模糊</option>");
                commonSelect.append(eaualOp);
                commonSelect.append(greaterOp);
                commonSelect.append(lessthanOp);
                commonSelect.append(greaterEqualOp);
                commonSelect.append(lessthanEqualOp);
                commonSelect.append(likeOp);
               searchObj.operator && commonSelect.find("option[value='"+searchObj.operator+"']").attr("selected",true);
                var input = $('<input/>').attr({
                    type: "text",
                    id: e.mysqlfieldname,
                    class: "form-control",
                    placeholder: "yyyy-MM-dd HH:mm:ss"
                }).val(searchObj.searchValue||'');
                var label = $("<label>"+e.fieldname+"：</label>");
                var li = $("<li></li>").append(label).append(commonSelect).append(input);
                ul.append(li);
            }else{

                var commonSelect = $("<select style='width: 80px'></select>").attr({
                    name: e.mysqlfieldname+"_1select",
                    id: e.mysqlfieldname+"_1select"
                });
                var eaualOp = $("<option value=\"EQUAL\">等于</option>");
                var greaterOp = $("<option value=\"GREATER\">大于</option>");
                var lessthanOp = $("<option value=\"LESSTHAN\">小于</option>");
                var greaterEqualOp = $("<option value=\"GREATER_EAUAL\">大于等于</option>");
                var lessthanEqualOp = $("<option value=\"LESSTHAN_EQUAL\">小于等于</option>");
                var likeOp = $("<option value=\"LIKE\">模糊</option>");
                commonSelect.append(eaualOp);
                commonSelect.append(greaterOp);
                commonSelect.append(lessthanOp);
                commonSelect.append(greaterEqualOp);
                commonSelect.append(lessthanEqualOp);
                commonSelect.append(likeOp);
                searchObj.operator && commonSelect.find("option[value='"+searchObj.operator+"']").attr("selected",true);
                var input = $('<input />').attr({
                    type: "text",
                    'data-id': e.id,
                    name: e.mysqlfieldname
                }).val(searchObj.searchValue||'');
                var label = $("<label>"+e.fieldname+"：</label>");
                var li = $("<li></li>").append(label).append(commonSelect).append(input);
                if(e.fieldtype=='2'){
                    var choose = $('<a class="fieldChoose" data-id="'+e.id+'" style="margin-left: 20px;">选择</a>');
                    li = li.append(choose);
                }
                ul.append(li);
            }
            searchParamsField.push(e);
        });
            var buttons0 = $("<a class=\"btn btn-primary btn-rounded btn-sm\" onclick=\"queryTable()\"><i class=\"fa fa-search\"></i>&nbsp;搜索</a>");
            var buttons1 = $("<a class=\"btn btn-warning btn-rounded btn-sm\" onclick=\"reset()\"><i class=\"fa fa-refresh\"></i>&nbsp;重置</a>");
            var buttons2 = $("<a class=\"btn btn-success btn-rounded btn-sm\" onclick=\"addRow()\"><i class=\"fa fa-plus\"></i>&nbsp;新增</a>");
            var li = $("<li></li>").append(buttons0).append(buttons1).append(buttons2)
            ul.append(li);
            $("#searchrow").html(ul);
            searchParamsField.forEach((field)=>{
                $("#"+field.mysqlfieldname).datetimepicker({
                format: "yyyy-mm-dd hh:ii:ss",
                autoclose: true
            });
        });
    }
    // 更新数据通过选择方式
    function updateDataByChoose(id,value){
        $("input[data-id='"+id+"']").val(value);
    }
</script>
</body>
</html>